package com.cens.mall.commodity.exception;

import com.cens.common.exception.BaseCodeEnum;
import com.cens.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.text.MessageFormat;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestControllerAdvice(basePackages = "com.cens.mall.commodity.controller")
public class MallControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e){
        log.error(MessageFormat.format("param valid error, message:{0}",e.getMessage()),e);
        BindingResult result = e.getBindingResult();
        if(result.hasErrors()){
            Map<String, Object> map = result.getFieldErrors().stream()
                    .collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            return R.error(BaseCodeEnum.VALID_EXCEPTION.getCode(),BaseCodeEnum.VALID_EXCEPTION.getMsg()).put("data",map);
        }
        return R.error(400,"数据校验异常！");
    }

    @ExceptionHandler(value = Exception.class)
    public R handleException(Exception e){
        log.error(MessageFormat.format("method error, message:{0}",e.getMessage()),e);
        return R.error(BaseCodeEnum.UNKNOWN_EXCEPTION.getCode(),BaseCodeEnum.UNKNOWN_EXCEPTION.getMsg());
    }
}
